package com._21cn.cms.resource.utils.upload.handler;

import com._21cn.cms.common.Constants;
import com._21cn.cms.resource.config.PictureConfig;
import com._21cn.cms.resource.entity.Picture;
import com._21cn.cms.resource.utils.UploadHelper;
import com._21cn.cms.resource.utils.PictureManager;
import com._21cn.cms.resource.utils.upload.UploadHandlerAdapter;
import com._21cn.framework.utils.FileUtil;
import com._21cn.framework.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图片上传处理类
 *
 * @author chenjh
 */
@Component("pictureUploadHandler")
public class PictureUploadHandler extends UploadHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(PictureUploadHandler.class);

    @Autowired
    private PictureManager pictureManager;

    private PictureConfig pictureConfig = new PictureConfig();          //图片配置项

    @Override
    public boolean beforeUpload(HttpServletRequest request, HttpServletResponse response) {

        //todo
        return true;
    }

    @Override
    public Map<UploadHelper.UploadResultType, List<Object>> afterUpload(Map<UploadHelper.UploadResultType,
            Map<String, File>> map, HttpServletRequest request, HttpServletResponse response) {

        Map<UploadHelper.UploadResultType, List<Object>> resultMap = new HashMap<UploadHelper.UploadResultType, List<Object>>();
        List<Object> success = new ArrayList<Object>();
        List<Object> fail = new ArrayList<Object>();
        resultMap.put(UploadHelper.UploadResultType.SUCCESS, success);
        resultMap.put(UploadHelper.UploadResultType.FAIL, fail);

        Picture picture = null;

        for (String key : map.get(UploadHelper.UploadResultType.FAIL).keySet()) {
            picture = new Picture();
            picture.setTitle("上传失败！");
            picture.setFileName(key);
            fail.add(picture);
        }

        for (String key : map.get(UploadHelper.UploadResultType.SUCCESS).keySet()) {
            picture = new Picture();
            picture.setTempFile(map.get(UploadHelper.UploadResultType.SUCCESS).get(key));
            String ext = FileUtil.getFileType(picture.getTempFile().getName());
            if (ext != null && ext.matches(pictureConfig.getAllowedPictureFile())) {
                picture.setTitle(key.substring(0, key.lastIndexOf(".")));
                picture.setFileName(key);
                picture.setExtName(key.substring(key.lastIndexOf(".") + 1).toLowerCase());
                if (StringUtil.isEmpty(picture.getExtName())){
                    picture.setExtName("jpg");
                }
                picture.setStatus(Constants.STATUS_ENABLE);
                picture = pictureManager.savePictureFile(picture);
                afterSave(success, fail, picture);
            }
//
        }
//        if (log.isDebugEnabled())
//            log.debug("resultMap:" + JSON.toJSONString(resultMap, true));
        return resultMap;
    }


    /**
     * 把处理后的图片加入到相应的列表，如果picture的tempFile不为空就是处理失败的
     *
     * @param success
     * @param fail
     * @param p
     */
    private void afterSave(List<Object> success, List<Object> fail, Picture p) {
        if (log.isDebugEnabled())
            log.debug("after save");
        if (p.getTempFile() != null) {
            fail.add(p);
        } else {
            success.add(p);
        }
    }

}